##kafka实时票房

from io import BytesIO
from PIL import Image
from kafka import KafkaProducer, producer
import time
from aip import AipOcr
from selenium import webdriver
import json
#9092
#连接百度Ocr
APP_ID = '24217351'
API_KEY = '7vRbBsMqcMPyFqry1nxwTdrH'
SECRET_KEY = 'LqoitsxibGBdy149lHlIOzBueTEHE8Nv'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

#图片转文字
def get_word(path):
    print('正在向baiduAip请求文字识别结果...')
    img = open(path, 'rb').read()
    options = {}
    options["language_type"] = "CHN_ENG"
    res = client.basicGeneral(img, options)
    res = res.get('words_result')[0].get('words')
    return res

#处理识别出来的数字
def correct(memory,officeBoxCount):
    if(not '.' in officeBoxCount or officeBoxCount[-1] == '.'):
        return memory + 0.2
    return float(officeBoxCount)

def getOfficeBoxCount():
    officeBoxCount_png = driver.find_element_by_xpath('//span[@class="mtsi-num"]').screenshot_as_png
    Image.open(BytesIO(officeBoxCount_png)).save('officeBoxCount.png')
    officeBoxCount = get_word('officeBoxCount.png')
    return officeBoxCount



options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('blink-settings=imagesEnabled=false')
driver = webdriver.Chrome(executable_path='/Users/aaa/py/chromedriver',options=options)
driver.get('https://piaofang.maoyan.com/dashboard/movie')
time.sleep(3)
#现在没有记忆
memory = 0
#生产者
producer = KafkaProducer(bootstrap_servers=['106.13.117.37:9092'])
while True:
    res = round(correct(memory,getOfficeBoxCount()),1)
    print(res)
    memory = res
    data = {
        'box':res
    }
    msg = json.dumps(data).encode()
    future = producer.send('officeBoxCount',value=msg,partition=None,key=None,timestamp_ms=None)
    result = future.get(timeout= 10)
    time.sleep(5)


